/*
Pickin' Open Sticks
Homepage:   http://code.google.com/p/pickin-open-sticks/
License:    GNU GPL v3 http://www.gnu.org/licenses/gpl.html
*/

#ifndef SINGLETON_H
#define SINGLETON_H
#include <string.h>

/**
 * @author Luke Fangel
 * @class Singleton
 * the singleton class provides a template for all singlton classes
 * @example class Foo : public Singleton<Foo> {}; not Foo is a singleton class
 **/

namespace pe
{

template<typename T>
    class Singleton {
        static T* ms_singleton;
    public:

        Singleton() {
            size_t offset = (size_t) (T*) 1 - (size_t) (Singleton <T>*)(T*) 1;
            ms_singleton = (T*) ((size_t)this +offset);
        }

        ~Singleton() {
            if (ms_singleton) delete ms_singleton;
            ms_singleton = 0;
        }

        static T& GetSingleton() {
            if (!ms_singleton)
                ms_singleton = new T;
            return *ms_singleton;
        }

        static T* GetSingletonPtr() {
            if (!ms_singleton)
                ms_singleton = new Singleton<T>;
            return ms_singleton;
        }
    };

    template <typename T> T* Singleton <T>::ms_singleton = 0;
}

#endif // SINGLETON_H
